<template>
  <div class="roles">
    <el-dialog title="分配权限" :visible="showRoles">
      <el-tree
        ref="tree"
        :data="data"
        show-checkbox
        default-expand-all
        node-key="id"
        check-strictly
        :props="defaultProps"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleById } from '@/api/role'
import { getAllPermissionApi, setAssignPremApi } from '@/api/permission'
export default {
  props: {
    showRoles: Boolean
  },
  data() {
    return {
      defaultProps: {
        label: 'name'
      },
      data: [],
      permIds: [],
      id: ''
    }
  },
  created() {
    this.getAllPermission()
  },
  methods: {
    cancel() {
      this.$emit('update:showRoles', false)
    },
    async submit() {
      try {
        this.permIds = this.$refs.tree.getCheckedKeys()
        await setAssignPremApi({
          id: this.id,

          permIds: this.permIds
        })
        this.$message.success('成功修改')
        this.$emit('update:showRoles', false)
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    trunData(arr, str) {
      return arr.filter(item => {
        if (item.pid === str) {
          item.children = this.trunData(arr, item.id)
          return true
        }
      })
    },
    async getAllPermission() {
      const res = await getAllPermissionApi()
      //   console.log(res)
      this.data = this.trunData(res, '0')
      //   console.log(this.data)
    },
    async getRoleById(id) {
      this.id = id
      const res = await getRoleById(id)

      //   console.log(res)
      this.permIds = res.permIds
      this.$refs.tree.setCheckedKeys(this.permIds)
    }
  }
}
</script>

<style></style>
